import { writeFileSync, readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'https://yaolifeng.com';

// 从文件中提取数据，通过正则表达式解析
function extractDataFromFile(filePath) {
    try {
        const content = readFileSync(filePath, 'utf-8');

        // 匹配数组数据
        const arrayMatch = content.match(/export default\s*\[([\s\S]*?)\];?\s*$/);
        if (!arrayMatch) {
            return [];
        }

        // 提取每个对象
        const objRegex = /{\s*"id":\s*"[^"]+",[\s\S]*?}/g;
        const objects = [];
        let match;

        while ((match = objRegex.exec(arrayMatch[1])) !== null) {
            const objStr = match[0];
            try {
                // 提取关键字段
                const slugMatch = objStr.match(/"slug":\s*"([^"]+)"/);
                const createdAtMatch = objStr.match(/"createdAt":\s*(\d+)/);
                const titleMatch = objStr.match(/"title":\s*"([^"]+)"/);

                if (slugMatch && createdAtMatch && titleMatch) {
                    objects.push({
                        slug: slugMatch[1],
                        createdAt: parseInt(createdAtMatch[1]),
                        title: titleMatch[1]
                    });
                }
            } catch (e) {
                console.warn('解析对象失败:', e.message);
            }
        }

        return objects;
    } catch (error) {
        console.error(`读取文件失败: ${filePath}`, error);
        return [];
    }
}

// 获取数据源
function getDataSources() {
    const projectRoot = join(__dirname, '..');

    // 读取博客数据
    const blogsPath = join(projectRoot, 'src/data/blogs/blogs.js');
    const blogs = extractDataFromFile(blogsPath);

    // 读取短文数据
    const shortsPath = join(projectRoot, 'src/data/shorts/shorts.js');
    const shorts = extractDataFromFile(shortsPath);

    return { blogs, shorts };
}

// 格式化日期为ISO字符串
function formatDate(timestamp) {
    return new Date(timestamp).toISOString();
}

// 生成URL条目
function generateUrlEntry(url, lastmod, changefreq = 'weekly', priority = 0.8) {
    return `    <url>
        <loc>${url}</loc>
        <lastmod>${lastmod}</lastmod>
        <changefreq>${changefreq}</changefreq>
        <priority>${priority}</priority>
    </url>`;
}

// 生成sitemap内容
function generateSitemap() {
    const { blogs, shorts } = getDataSources();

    const urls = [];

    // 添加静态页面
    const staticPages = [
        { path: '', priority: 0.7, changefreq: 'daily' },
        { path: '/blog', priority: 0.7, changefreq: 'daily' },
        { path: '/shorts', priority: 0.7, changefreq: 'daily' },
        { path: '/about', priority: 0.7, changefreq: 'daily' },
        { path: '/projects', priority: 0.7, changefreq: 'daily' },
        { path: '/services', priority: 0.7, changefreq: 'daily' },
        { path: '/links', priority: 0.7, changefreq: 'daily' }
    ];

    staticPages.forEach(page => {
        urls.push(generateUrlEntry(
            `${SITE_URL}${page.path}`,
            new Date().toISOString(),
            page.changefreq,
            page.priority
        ));
    });

    // 添加博客页面
    blogs.forEach(blog => {
        urls.push(generateUrlEntry(
            `${SITE_URL}/blog/${blog.slug}`,
            formatDate(blog.createdAt),
            'weekly',
            0.8
        ));
    });

    // 添加短文页面
    shorts.forEach(short => {
        urls.push(generateUrlEntry(
            `${SITE_URL}/shorts/${short.slug}`,
            formatDate(short.createdAt),
            'weekly',
            0.8
        ));
    });

    // 生成完整的sitemap XML
    const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
    xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
    xmlns:xhtml="http://www.w3.org/1999/xhtml"
    xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0"
    xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
    xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
${urls.join('\n')}
</urlset>
`;

    return sitemap;
}

// 主函数
function main() {
    try {
        console.log('🚀 开始生成 sitemap...');

        const sitemap = generateSitemap();
        const outputPath = join(process.cwd(), 'public', 'sitemap.xml');

        writeFileSync(outputPath, sitemap, 'utf8');

        console.log('✅ sitemap.xml 已生成到:', outputPath);
        console.log('📊 统计信息:');

        const { blogs, shorts } = getDataSources();
        console.log(`   - 博客文章: ${blogs.length} 篇`);
        console.log(`   - 短文: ${shorts.length} 篇`);
        console.log(`   - 静态页面: 7 个`);
        console.log(`   - 总计URL: ${blogs.length + shorts.length + 7} 个`);

    } catch (error) {
        console.error('❌ 生成 sitemap 时发生错误:', error);
        process.exit(1);
    }
}

// 运行脚本
main();
